package launcher.simple.android.woblog.cn.simplelauncher;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.peripheral.BluetoothHfDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.bluetooth.BluetoothProfile;

import cn.woblog.android.common.utils.activity.BaseActivity;
import launcher.simple.android.woblog.cn.system.CallInfo;
import launcher.simple.android.woblog.cn.system.InCallManager;
import launcher.simple.android.woblog.cn.system.PhoneState;
import launcher.simple.android.woblog.cn.widget.AlertDialogFragment;


public class InCallActivity extends BaseActivity implements InCallManager.OnPhoneStateChangedListener, InCallManager.OnInfoChangedListener {
    private static final String TAG = "InCallActivity";

    private static final int MSG_FORCE_FINISH = -1;
    private static final int MSG_TIMER = 0;

    private PowerManager mManager;
    private InCallManager mCallManager;
    private TextView tv_name;
    private TextView tv_type;
    private ImageView iv_endcall;
    private ImageView iv_call;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothHfDevice.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED);
                if (state == BluetoothProfile.STATE_DISCONNECTED) {
                    finish();
                }
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                mCallManager.manualMute();
            }
        }
    };


    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_FORCE_FINISH:
                    mCallManager.hangup();
                    break;
                case MSG_TIMER:
//                    if (mTimeView != null) {
//                        mTimeView.setText(formatTime(msg.arg1));
//                    }
                    break;
                default:
                    break;
            }
        };
    };
    private PowerManager.WakeLock mWakeLock;
    private PowerManager.WakeLock wakeLock;
    private PowerManager.WakeLock wl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_in_call);
        BluetoothAdapter adb = BluetoothAdapter.getDefaultAdapter();
        if (!adb.isEnabled()) {
            showBtDisableDialog();
            return;
        }

        mManager = (PowerManager) getSystemService(POWER_SERVICE);
        mCallManager = InCallManager.getDefault();
        mCallManager.setOnPhoneStateChangedListener(this);
        mCallManager.setOnInfoChangedListener(this);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_type = (TextView) findViewById(R.id.tv_type);
        iv_endcall = (ImageView) findViewById(R.id.iv_endcall);
        iv_call = (ImageView) findViewById(R.id.iv_call);
//        mTimeView = (TextView) findViewById(R.id.time);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(BluetoothHfDevice.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(mReceiver, filter);

        final String action = getIntent().getAction();
        String number = getIntent().getStringExtra(PhoneState.EXTRA_NUMBER);
        if (InCallManager.ACTION_OUT_CALL.equals(action)) {
            Log.i(TAG, "dial:" + mCallManager.isBtConnected());
            CallInfo info = new CallInfo(this, null, number);
            mCallManager.dial(info);
            mHandler.sendEmptyMessageDelayed(MSG_FORCE_FINISH, 90000);
        } else if (InCallManager.ACTION_INCOMING_CALL.equals(action)) {
            mCallManager.onRing();
            mHandler.sendEmptyMessageDelayed(MSG_FORCE_FINISH, 60000);
        } else {
            finish();
            return;
        }

        if (mWakeLock == null) {
            mWakeLock = mManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "keep_cpu");
        }
        mWakeLock.acquire();
    }

    /**
     * 显示蓝牙未打开对话框
     */
    private void showBtDisableDialog() {
        AlertDialogFragment open = new AlertDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString(AlertDialogFragment.EXTRA_TITLE,
                getString(R.string.title_bt_disabled));
        bundle.putString(AlertDialogFragment.EXTRA_MESSAGE,
                getString(R.string.message_bt_disabled));
        bundle.putInt(AlertDialogFragment.EXTRA_POSITIVE, android.R.string.ok);
        open.setArguments(bundle);
        open.setOnClickListener(new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        open.show(getFragmentManager(), "open");
    }

    @Override
    protected void initDatas() {
        super.initDatas();

    }

    private void keepScreen() {
        if (wakeLock == null) {
            wakeLock = mManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "keep_screen");
        }
        wakeLock.acquire();
    }

    private void unKeepScreen() {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    private void acquireWakelock() {
        if (wl == null) {
            wl = mManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "turn_screen");
        }
        if (!wl.isHeld()) {
            wl.acquire(15000);
        }
    }
    @Override
    public void onPhoneStateChanged(int state) {
        Log.i(TAG, "onPhoneStateChanged:" + state);
//        if (waitingDialog != null && waitingDialog.isShowing()) {
//            dismissDialog(Utils.HF_DEVICE_CALL_WAITING_DIALOG_ID);
//        }
        if (state == PhoneState.STATE_RINGING) {
            keepScreen();
        } else {
            unKeepScreen();
            acquireWakelock();
        }
        if (state != PhoneState.STATE_DIALING && state != PhoneState.STATE_RINGING) {
            if (mHandler.hasMessages(MSG_FORCE_FINISH)) {
                mHandler.removeMessages(MSG_FORCE_FINISH);
            }
        }
        if (state == PhoneState.STATE_IDLE) {
            finish();
            return;
        }
        updateInfo(mCallManager.getRemoteInfo());
//        switch (state) {
//            case PhoneState.STATE_DIALING:
//                hideFunction(FUNCTION_ANSWER);
//                hideFunction(FUNCTION_SMS_PAD);
//                break;
//            case PhoneState.STATE_RINGING:
//                if (!mCallManager.isBtConnected()) {
//                    hideFunction(FUNCTION_ANSWER);
//                }
//                if (!mCallManager.isBond()) {
//                    hideFunction(FUNCTION_SMS_PAD);
//                }
//                if (!mCallManager.isBtConnected() && !mCallManager.isBond()) {
//                    showFunction(FUNCTION_ANSWER);
//                    setFunctionEnabled(FUNCTION_HANGUP, false);
//                    setFunctionEnabled(FUNCTION_ANSWER, false);
//                }
//                if (!Utils.HF_ENABLE) {
//                    hideFunction(FUNCTION_ANSWER);
//                }
//                break;
//            case PhoneState.STATE_OFFHOOK:
//                showFunction(FUNCTION_SMS_PAD);
//                hideFunction(FUNCTION_ANSWER);
//                setFunctionRescource(FUNCTION_SMS_PAD, R.drawable.btn_pad);
//                break;
//            default:
//                break;
//        }
//        if (state == PhoneState.STATE_OFFHOOK) {
//            startTimer();
//            mTimeView.setText(formatTime(mTimeLeft));
//        } else {
//            stopTimer();
//            updateState(state);
//        }
    }

    @Override
    public void onInfoChanged(CallInfo info) {
        updateInfo(info);
    }

    private void updateInfo(CallInfo info) {
        if (info == null) {
            tv_name.setVisibility(View.GONE);
//            mNumberView.setVisibility(View.GONE);
            return;
        }
        String name = info.getRemoteName();
        if (TextUtils.isEmpty(name)) {
            tv_name.setVisibility(View.GONE);
        } else {
            tv_name.setVisibility(View.VISIBLE);
            tv_name.setText(name);
        }
//        mNumberView.setText(info.getRemoteNumber());
    }
}
